clear
discard
set more off

adopath ++ "./ado/"
adopath ++ "../tools/"
adopath ++ "../ssc/"

******************
*** Parameters ***
******************

local file_name "./input/consensus_dataset.csv"  // Data file
local output_folder "./output/rolling" // Output directory
local L_NW = 5 // Number of lags for calculating Newey-West standard errors

*************************************
*** Import data and set data type ***
*************************************

import delimited using `file_name', case(preserve)
rename DATE Date

gen qtr = quarterly(Date,"YQ")
format qtr %tq
tsset qtr // Set to time series

********************************
*** Generate forecast errors ***
********************************

* Clean up
shell rm -r `output_folder'
shell mkdir -p ./output
shell mkdir `output_folder'

* Generate variables
gen Efor_Step2 = Realiz1 - SPFfor_Step2
forvalues k = 1/4 {
	quietly gen l`k'_Efor_Step2 = l`k'.Efor_Step2
	quietly gen l`k'_Realiz1 = l`k'.Realiz1
}

******************
*** Estimation ***
******************

* Rolling regressions
rolling _b _se e(N) e(df_r), window(32) saving(IRF_LP_1Q_ahead, replace) keep(Date) reject(e(N) < 32): ///
	newey f0.Efor_Step2 l1_Efor_Step2 l2_Efor_Step2 l3_Efor_Step2 l4_Efor_Step2, lag(`L_NW')
rolling _b _se e(N) e(df_r), window(32) saving(IRF_actual, replace) keep(Date) reject(e(N) < 32): ///
	newey f0.Realiz1 l1_Realiz1 l2_Realiz1 l3_Realiz1 l4_Realiz1, lag(`L_NW')

* Save results
clear
use IRF_LP_1Q_ahead.dta
rename _b_l1_Efor_Step2 IRF
rename _se_l1_Efor_Step2 se
rename _eq2_stat_2 df_resid
export delimited date IRF se df_resid using `output_folder'/rolling_IRF_1Q_ahead.csv

clear
use IRF_actual.dta
rename _b_l1_Realiz1 IRF
rename _se_l1_Realiz1 se
rename _eq2_stat_2 df_resid
export delimited date IRF se df_resid using `output_folder'/rolling_IRF_actual.csv

clear
shell rm ./IRF_LP_1Q_ahead.dta
shell rm ./IRF_actual.dta
